﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Outlook;
using ToodleDo;
using Folder = Toodledo.Model.Folder;

namespace Sync
{
    class FolderSync
    {
        #region Members

        
        #endregion

        #region Constructors & Init
        public FolderSync()
        {
            
        }
        #endregion

        #region Public Methods

        public void Sync()
        {            
            
            AddNewToServer();
            DeleteFromServer();
            UpdateFolders();
            
            
            
            //Delete empty folders from Remote
            //todo cleanse folders from both sides
        }
        #endregion

        #region #Events & Invokables

        #endregion

        #region Private Methods
        private void AddNewToServer()
        {
            //new are: not present in previous sync

            List<Category> nonemptyoutlookfolders = new List<Category>(global::Sync.Outlook.OutlookCategories.NonEmptyFolders);
            foreach (Category c in nonemptyoutlookfolders)
            {
                if(!SyncSessionWrapper.SyncSession.Folders.Exists(f=>f.Name==c.Name))
                {
                    Remote.General.AddFolder(c.Name, false);
                }
            }           
        }

        private void DeleteFromServer()
        {
            List<Category> alloutlookcategories = new List<Category>(global::Sync.Outlook.OutlookCategories.All);
            foreach (Toodledo.Model.Folder f in SyncSessionWrapper.SyncSession.Folders)
            {
                if (!alloutlookcategories.Exists(fold => fold.Name == f.Name))
                {
                    Remote.General.DeleteFolder(f.Id);
                }
            }           
        }

        private void UpdateFolders()
        {
            List<Category> allcategories = Outlook.OutlookCategories.All.ToList();
            //add if exists
            //old set
            List<Folder> oldset = SyncSessionWrapper.SyncSession.Folders;
            SyncSessionWrapper.SyncSession.Folders = new List<Toodledo.Model.Folder>(Remote.General.GetFolders());
            //Add new folders to Outlook
            foreach (Toodledo.Model.Folder folder in SyncSessionWrapper.SyncSession.Folders)
            {
                if (!allcategories.Exists(c => c.Name == folder.Name))
                    Outlook.OutlookCategories.Add(folder);
            }
            foreach (Folder folder in oldset)
            {
                //todo delete folders from outlook
            }
            //Add new folders(not empty) to Server
            //delete folders that are not referenced

            //compare the doubles, and prepare edits;
        }

        #endregion

        #region EventHandlers

        #endregion
    }
}
